<template>
  <div>
    <Navbar
      :appTitle="appTitle"
      :rname="isShowScan ? 'scan' : ''"
      @ClickRight="clickCode('', '', true)"
    />
    <div
      class="form-content wrap-apply"
      :style="{
        top: GLOBAL.currentEnvironment ? '0' : '',
        height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 100px)',
        paddingBottom: GLOBAL.currentEnvironment ? '120px' : '',
      }"
    >
      <van-cell-group class="formItemFlex">
        <p class="label required FormTit"><span></span>盘盈单编号</p>
        <div class="haveUnitBox">
          <van-field
            v-model="buildForm.taskCode"
            :maxLength="50"
            placeholder="请输入、不输入则自动生成"
            input-align="right"
            readonly
          />
        </div>
      </van-cell-group>
      <div class="bottomLine"></div>
      <van-cell-group class="formItemFlex">
        <p class="label FormTit"><span></span>单据日期</p>
        <div class="haveUnitBox">
          <van-field
            input-align="right"
            readonly
            v-model="buildForm.operateTime"
            placeholder="请选择"
          />
        </div>
        <div class="bottomLine"></div>
      </van-cell-group>

      <div class="list">
        <div
          class="wrap"
          v-for="(p, i) in entryDetails"
          :key="p.goodsKey"
          v-show="entryDetails.length != 0"
          style="margin-bottom: 10px;"
        >
          <van-cell-group>
            <p class="label otherText">
              <span>盘盈明细（{{ i + 1 }}）</span>
              <span class="deleteStyle" @click="deleteGoods(i)">删除</span>
            </p>
            <div class="bottomLine"></div>
            <div class="top">
              <div class="icon"></div>
              <div class="title titleWidth">
                {{ p.goodsCode }}| {{ p.goodsName }}| {{ p.spec }}
              </div>
            </div>
            <div class="center">
              <div>
                <p>
                  <span class="key">包装规格：</span>
                  <span class="value">{{ p.packageSpec }}</span>
                </p>
                <p>
                  <span class="key">产地：</span>
                  <span class="value">{{ p.address }}</span>
                </p>
                <p>
                  <span class="key">基本单位：</span>
                  <span class="value">{{ p.unitName }}</span>
                </p>
              </div>
            </div>
            <van-cell-group class="formItemFlex">
              <p class="label required FormTit"><span></span>批号</p>
              <div class="haveUnitBox">
                <van-field
                  v-model="p.batchCode"
                  placeholder="请选择"
                  input-align="right"
                  readonly
                  @click="showBatchCode(p, i)"
                >
                  <template #right-icon>
                    <div style="display: flex;">
                      <van-icon
                        @click="showBatchCode(p, i)"
                        size="20"
                        color="#999"
                        name="arrow"
                        style="margin-top: 2px"
                      />
                    </div>
                  </template>
                </van-field>
              </div>
            </van-cell-group>
            <div class="bottomLine"></div>
            <van-cell-group class="formItemFlex">
              <p class="label required FormTit"><span></span>盘点库位</p>
              <div class="haveUnitBox">
                <van-field
                  v-model="p.latticeFullname"
                  placeholder="请选择或扫码"
                  input-align="right"
                  readonly
                  @click="showLatticeNotification(p, i)"
                >
                  <template #right-icon>
                    <div style="display: flex;">
                      <van-icon
                        @click="showLatticeNotification(p, i)"
                        size="20"
                        color="#999"
                        name="arrow"
                        style="margin-top: 2px"
                      />
                      <van-icon
                        @click.stop="clickCode(p, i, false)"
                        size="20"
                        color="#999"
                        name="scan"
                        style="margin-top: 2px"
                      />
                    </div>
                  </template>
                </van-field>
              </div>
            </van-cell-group>
            <div class="bottomLine"></div>
            <van-cell-group class="formItemFlex">
              <p class="label required FormTit"><span></span>盘盈数</p>
              <div class="haveUnitBox">
                <van-field
                  v-model="p.profitNum"
                  type="number"
                  placeholder="请输入"
                  input-align="right"
                  :formatter="(e) => needInNumChange(e)"
                />
              </div>
            </van-cell-group>
          </van-cell-group>
        </div>

        <div class="addGoodScontain">
          <div class="addgoods" @click="addInventoryGoods">
            <van-icon
              name="plus"
              size="16px"
              color="#1890ff"
              style="top: 2px"
            />
            <a>物品</a>
          </div>
        </div>
      </div>

      <div class="search-bottoms">
        <van-button
          class="btnconfirm"
          :loading="subLoading"
          loading-text="提交中..."
          @click="btnConfirm"
          >提交</van-button
        >
      </div>
    </div>
    <!--选择物品 -->
    <goods-pickers-ak
      v-if="showGoodsPicker"
      :listUrl="listUrl"
      :columns="goodsColumns"
      :selectedGoods="[]"
      @getCheckedGoods="getCheckedGoods"
    ></goods-pickers-ak>
    <!--选择批号 -->
    <batchCode-pickers-ak
      v-if="isShowbatchCode"
      :listUrl="batchCodeUrl"
      :columns="batchCodeColumns"
      :usedOutBox="false"
      :selectedGoods="[]"
      @handleList="handleBatchCodeList"
    ></batchCode-pickers-ak>
    <!--选择库位 -->
    <binLocation-pickers-ak
      v-if="isShowLatticeNotification"
      :listUrl="latticeNotificationUrl"
      :columns="latticeNotificationgColumns"
      :selectedGoods="[]"
      @handleList="handleList"
    ></binLocation-pickers-ak>
    <!-- 浏览器扫码组件 -->
    <qrcode
      :qrcode="codeForm.qrcode"
      :showClose="codeForm.showClose"
      v-show="codeForm.qrcode"
      :camera="camera"
      :torchActive="torchActive"
      @switchCamera="switchCamera"
      @ClickFlash="ClickFlash"
      @turnCameraOff="turnCameraOff"
      @onDecode="onDecode"
      @onInit="onInit"
    />
    <!-- 激光扫码组件 -->
    <PDAsao @changeScan="changeScan2" />
  </div>
</template>
<script>
import moment from "moment";
import Navbar from "@/components/navBar/navBar_right";
import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import GoodsPickersAk from "@/components/choiceuse/GoodsPickersAk";
import { genEntityCode, addWmsProOrLoss, getWarehouseLatticeDetail } from "@/api/inventoryOrder";
import { getLatticeInfoForScan } from "@/api/removeAndinventory";
import store from "@/store";
import BinLocationPickersAk from "@/components/choiceuse/BinLocationPickersAk";
import batchCodePickersAk from "@/components/choiceuse/batchCodePickersAk";
import PDAsao from "@/components/scanCode/PDAsao.vue";

export default {
  name: "warehousingTaskForm",
  components: {
    Navbar,
    VanFieldSelectPicker,
    GoodsPickersAk,
    BinLocationPickersAk,
    batchCodePickersAk,
    qrcode: () => import("@/components/scanCode"),
    PDAsao,
  },
  data() {
    return {
      appTitle: "新建盘盈单",
      buildForm: {
        taskCode: "",
        operateType: "3",
        operateTime: "",
      },
      showGoodsPicker: false,
      listUrl: "/baseSetting/wmsGoods/queryByPage",
      goodsColumns: {
        titleKey: ["goodsCode", "goodsName", "spec"], //标题
        content: [
          //内容
          {
            name: "产地",
            key: ["address"],
          },
          {
            name: "包装规格",
            key: ["packageSpec"],
          },
          {
            name: "单位",
            key: ["unitIdText"],
          },
        ],
        operationText: "",
      },

      isShowbatchCode: false,
      batchCodeUrl: "/wmsgoodsnotification/getBatchCode",
      batchCodeColumns: {
        titleKey: ["batchCode", "produceDate"], //标题
        content: [
          //内容
          {
            name: "所在库位",
            key: ["latticeInfo"],
          },
          {
            name: "库位库存",
            key: ["latticeNum"],
          },
          {
            name: "库存总数",
            key: ["goodsNum"],
          },
        ],
      },

      isShowLatticeNotification: false,
      latticeNotificationUrl: "/wmslattice/getLatticeNotificationInventory",
      latticeNotificationgColumns: {
        titleKey: ["latticeCode", "latticeName"], //标题
        content: [
          //内容
          {
            name: "排列层",
            key: ["locationInfo"],
          },
          {
            name: "库区名称",
            key: ["areaName"],
          },
          {
            name: "仓库名称",
            key: ["warehouseName"],
          },
        ],
        labelKey: [], //标签
        operationText: "",
      },

      entryDetails: [],
      recentGoodsIndex: "",
      subLoading: false,

      // 扫码相关
      codeForm: {
        qrcode: false,
        showClose: false,
      },
      torchActive: true,
      camera: "off",
      isshow: false,
    };
  },
  computed: {
    isShowScan() {
      if (
        this.showGoodsPicker ||
        this.isShowbatchCode ||
        this.isShowLatticeNotification
      ) {
        return false;
      } else {
        return true;
      }
    },
  },
  beforeRouteLeave(to, from, next) {
    if (
      this.showGoodsPicker ||
      this.isShowbatchCode ||
      this.isShowLatticeNotification
    ) {
      this.showGoodsPicker = false;
      this.isShowbatchCode = false;
      this.isShowLatticeNotification = false;
      this.appTitle = "新建盘盈单";
      next(false);
    } else {
      next();
    }
  },
  async created() {
    store.commit("SET_CURRENT_PREFIX", "/jksaas-produce/produce");
    this.initData();
  },
  methods: {
    // 重置form表单
    resetForm () {
      this.buildForm = {
        taskCode: "",
        operateType: "3",
        operateTime: "",
      }
      this.recentGoodsIndex = ""
      this.entryDetails = []
    },
    // 提交
    btnConfirm() {
      if (!this.buildForm.taskCode) {
        this.$toast(`请输入盘盈单编号`);
        return;
      }

      try {
        if (this.entryDetails && this.entryDetails.length > 0) {
          this.entryDetails.forEach((element, index) => {
            if (!element.batchCode) {
              throw new Error(`盘盈明细（${index + 1}）批号不可为空`);
            }
            if (!element.latticeId) {
              throw new Error(`盘盈明细（${index + 1}）盘点库位不可为空`);
            }
            if (!element.profitNum) { 
              throw new Error(`盘盈明细（${index + 1}）盘盈数不可为空`);
            }
          });
        } else {
          throw new Error(`请选择物品`);
        }
      } catch (error) {
        this.$toast(error.message);
        return false;
      }
      this.handleSubmit();
    },
    handleSubmit() {
      let params = {
        ...this.buildForm,
        profitOrLossGoodsDtos: this.entryDetails.map((ele) => {
          return {
            batchCode: ele.batchCode,
            goodsBatchId: ele.goodsBatchId,
            goodsId: ele.goodsId,
            latticeId: ele.latticeId,
            profitNum: ele.profitNum,
          };
        }),
      };
      this.subLoading = true;
      addWmsProOrLoss(params)
        .then((res) => {
          if (res.success) {
            this.$toast(res.message);
            this.initData();
          } else {
            this.$toast(res.message);
          }
          this.subLoading = false;
        })
        .catch(() => {
          this.subLoading = false;
        })
        .finally(() => {
          this.subLoading = false;
        });
    },
    // 初始化页面数据
    initData() {
      this.resetForm()
      // 盘盈单编号
      genEntityCode({ entityCode: "WMS_WAREHOUSE_INVENTORY_PROFIT" }).then(
        (res) => {
          if (res.code == 200) {
            this.buildForm.taskCode = res.result;
            this.buildForm.operateTime = moment(new Date()).format(
              "YYYY-MM-DD"
            );
          } else {
            this.buildForm.taskCode = "";
            this.$toast(res.message);
          }
        }
      );
    },
    // 盘盈单物品明细-》添加
    addInventoryGoods() {
      this.appTitle = "选择物品";
      this.showGoodsPicker = true;
    },
    // 盘盈单物品明细-》删除
    deleteGoods(i) {
      this.entryDetails.splice(i, 1);
    },
    // 确认选中物品 物品可复选
    async getCheckedGoods(list) {
      this.showGoodsPicker = false;
      this.appTitle = "新建盘盈单";

      let checkedGoods = list.map((son) => {
        let {
          id,
          goodsCode,
          goodsName,
          spec,
          address,
          packageSpec,
          unitIdText,
        } = son;
        return {
          goodsId: id || "",
          goodsKey: id + "_" + Math.floor(Math.random() * 1000),
          goodsCode: goodsCode || "-",
          goodsName: goodsName || "-",
          spec: spec || "-",
          address: address || "-",
          packageSpec: packageSpec || "-",
          unitName: unitIdText || "-",

          batchCode: "",
          goodsBatchId: "",
          latticeId: "",
          profitNum: "",
        };
      });

      this.entryDetails = this.entryDetails.concat(checkedGoods);
    },

    // 确认选中批号 单选
    handleBatchCodeList(binLocationid, item, text) {
      this.isShowbatchCode = false;
      this.appTitle = "新建盘盈单";
      let recGoods = this.entryDetails[this.recentGoodsIndex];

      try {
        this.entryDetails.forEach((ele) => {
          if (ele.goodsKey != recGoods.goodsKey) {
            if (
              ele.goodsId == recGoods.goodsId &&
              ele.latticeId == recGoods.latticeId
            ) {
              if (ele.goodsBatchId == item.goodsBatchId) {
                throw new Error(`同个物品、批号、盘点库位的组合不能重复`);
              }
            }
          }
        });
      } catch (error) {
        this.$toast(error.message);
        return false;
      }

      let { batchCode, goodsBatchId } = item;
      this.$set(this.entryDetails, this.recentGoodsIndex, {
        ...this.entryDetails[this.recentGoodsIndex],
        batchCode: batchCode,
        goodsBatchId: goodsBatchId,
      });
    },
    // 批号选择
    showBatchCode(item, index) {
      try {
        if (!item.goodsId || item.goodsId == "") {
          throw new Error(`物品数据异常`);
        }
      } catch (error) {
        this.$toast(error.message);
        return false;
      }

      this.batchCodeUrl = "";
      if (index != -1) {
        this.recentGoodsIndex = index;
        this.batchCodeUrl = `/wmsgoodsnotification/getBatchCode?goodsId=${item.goodsId}`;
        this.appTitle = "批号";
        this.isShowbatchCode = true;
      }
    },

    // 确认选中库位 单选
    handleList(binLocationid, item, text) {
      this.isShowLatticeNotification = false;
      this.appTitle = "新建盘盈单";
      let recGoods = this.entryDetails[this.recentGoodsIndex];

      try {
        this.entryDetails.forEach((ele) => {
          if (ele.goodsKey != recGoods.goodsKey) {
            if (
              ele.goodsId == recGoods.goodsId &&
              ele.goodsBatchId == recGoods.goodsBatchId
            ) {
              if (ele.latticeId == item.id) {
                throw new Error(`同个物品、批号、盘点库位的组合不能重复`);
              }
            }
          }
        });
      } catch (error) {
        this.$toast(error.message);
        return false;
      }

      let { id, latticeCode, latticeName } = item;
      this.$set(this.entryDetails, this.recentGoodsIndex, {
        ...this.entryDetails[this.recentGoodsIndex],
        latticeId: id,
        latticeCode: latticeCode,
        latticeName: latticeName,
        latticeFullname: latticeCode + "|" + latticeName,
      });
    },
    // 库位选择
    showLatticeNotification(item, index) {
      this.latticeNotificationUrl = "";
      if (index != -1) {
        this.recentGoodsIndex = index;
        this.latticeNotificationUrl = `/wmslattice/getLatticeNotificationProLoss`;
        this.appTitle = "库位";
        this.isShowLatticeNotification = true;
      }
    },

    // 盘盈单 盘盈数 数量处理
    needInNumChange(e) {
      let value = this.clearNoNum(e);
      return value
    },
    /*数量处理*/
    clearNoNum(value) {
      //先把非数字的都替换掉，除了数字和.
      value = value.replace(/[^\d.]/g, "");
      //保证只有出现一个.而没有多个.
      value = value.replace(/\.{2,}/g, ".");
      //必须保证第一个为数字而不是.
      value = value.replace(/^\./g, "");
      //保证.只出现一次，而不能出现两次以上
      value = value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      //只能输入四个小数
      value = value.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, "$1$2.$3");
      // console.log(value.includes('.'),'wwwwww')
      //小数位处理
      if (value.substring(0, 1) == "0" && value.substring(0, 2) != "0.") {
        value = '0';
      }
      //输入长度控制
      if (value > 9999999999.9999) {
        value = "";
      }

      return value;
    },

    // 扫码相关
    // 打开相机
    clickCode(item, index, isshow) {
      if (!this.isShowScan) {
        return false;
      }
      
      let that = this;
      this.recentGoodsIndex = index;
      this.isshow = isshow;

      let platform = localStorage.getItem("currentEnvironment");
      switch (platform) {
        case "iwork":
          var opt = {
            success: function(res) {
              console.log(JSON.stringify(res), "APP扫码数据");
              if (res.retCode == 0) {
                that.onDecode(res.retData);
              } else {
                that.$toast(res.retMsg);
              }
            },
            fail: function(err) {
              that.$toast("扫码失败！");
            },
          };
          //插件调用代码
          WorkHelper.scan(opt);
          break;
        case "browser":
          // camera:: 'front'--前摄像头，'rear'后摄像头，'off'关闭摄像头，会获取最后一帧显示，'auto'开始获取摄像头
          that.codeForm.qrcode = true;
          that.camera = "rear";
          break;
        case "dingding":
          dd.biz.util.scan({
            type: "qrCode", // type 为 all、qrCode、barCode，默认是all。
            onSuccess: function(data) {
              //onSuccess将在扫码成功之后回调
              that.onDecode(data.text);
            },
            onFail: function(err) {
              // console.error(err,'error')
            },
          });
          break;
        default:
          "";
          break;
      }
    },
    // 扫码结果回调
    onDecode(result) {
      // result, 扫描结果，可以根据自己的需求来实现相应的功能
      this.codeForm.code = JSON.parse(result);
      if (this.codeForm.code.EntityType == "lattice" && this.codeForm.code.id) {
        if (this.isshow) {
          // 扫库位码 获取库位关联物品
          let params = {
            id: this.codeForm.code.id,
            scope: "Inventory_pro_loss_sheet",
          };

          getLatticeInfoForScan(params).then((res) => {
            if (res.code == 200 && res.result) {
              if (res.result.length == 0) {
                this.$toast("该库位关联物品为空");
                this.clickCode("", this.recentGoodsIndex, true);
                return;
              }

              let newGoodsList = res.result.map((son) => {
                let {
                  goodsCode,
                  goodsName,
                  goodsId,
                  spec,
                  unitName,
                  packageSpec,
                  address,
                  batchCode,
                  goodsBatchId,
                  latticeId,
                  latticeName,
                  latticeCode,
                } = son;

                return {
                  detailId: "",

                  goodsKey: goodsId + "_" + Math.floor(Math.random() * 1000), // 物品基本数据
                  goodsId: goodsId || "",

                  goodsCode: goodsCode || "-",
                  goodsName: goodsName || "-",
                  spec: spec || "-",

                  packageSpec: packageSpec || "-",
                  address: address || "-",
                  unitName: unitName || "-",

                  batchCode: batchCode || "", // 批次数据
                  goodsBatchId: goodsBatchId || "",

                  latticeCode: latticeCode || "", // 库位数据
                  latticeName: latticeName || "",
                  latticeId: latticeId || "",
                  latticeFullname:
                    (latticeCode && latticeName)
                      ? latticeCode + "|" + latticeName
                      : "",

                  profitNum: '', // 盘盈数
                };
              });

              if (this.entryDetails.length != 0) {
                let array1Copy = this.mergeWithoutDuplicatesPreservingOriginals(
                  this.entryDetails,
                  newGoodsList
                );
                if (array1Copy.length != 0) {
                  this.entryDetails = this.entryDetails.concat(array1Copy);
                } else {
                  this.$toast("物品、批号、盘点库位已存在");
                }
              } else {
                this.entryDetails = newGoodsList;
              }

              this.turnCameraOff();
              this.isshow = false;
            } else {
              this.$toast(res.message);
            }
          });
        } else {
          // 扫库位码 获取库位
          getWarehouseLatticeDetail(this.codeForm.code.id).then((res) => {
            if (res.code == 200 && res.result) {
              if (res.result.status == "effective") {
                let recLat = res.result;
                this.turnCameraOff()
                this.handleList('', recLat, '')
              } else {
                this.$toast("该库位已被禁用");
                this.clickCode(recGoods, this.recentGoodsIndex, false);
              }
            } else {
              this.$toast(res.message);
            }
          });
        }
      } else {
        this.$toast("请扫正确二维码");
        if (this.isshow) {
          this.clickCode("", "", true);
        } else {
          this.clickCode(
            this.entryDetails[this.recentGoodsIndex],
            this.recentGoodsIndex,
            false
          );
        }
      }
    },
    // 相机反转
    switchCamera() {
      switch (this.camera) {
        case "front":
          this.camera = "rear";
          break;
        case "rear":
          this.camera = "front";
          break;
        default:
          this.$toast("错误");
      }
    },
    // 关闭相机
    turnCameraOff() {
      this.camera = "off";
      this.codeForm.qrcode = false;
    },
    // 打开手电筒
    ClickFlash() {
      switch (this.torchActive) {
        case true:
          this.torchActive = false;
          break;
        case false:
          this.torchActive = true;
          break;
        default:
          this.$toast("错误");
      }
    },
    // 检查是否调用摄像头
    async onInit(promise) {
      try {
        await promise;
      } catch (error) {
        if (error.name === "StreamApiNotSupportedError") {
        } else if (error.name === "NotAllowedError") {
          this.errorMessage = "Hey! I need access to your camera";
        } else if (error.name === "NotFoundError") {
          this.errorMessage = "Do you even have a camera on your device?";
        } else if (error.name === "NotSupportedError") {
          this.errorMessage =
            "Seems like this page is served in non-secure context (HTTPS, localhost or file://)";
        } else if (error.name === "NotReadableError") {
          this.errorMessage =
            "Couldn't access your camera. Is it already in use?";
        } else if (error.name === "OverconstrainedError") {
          this.errorMessage =
            "Constraints don't match any installed camera. Did you asked for the front camera although there is none?";
        } else {
          this.errorMessage = "UNKNOWN ERROR: " + error.message;
        }
      }
    },
    // 激光扫码
    changeScan2(v) {
      if (v.EntityType == "goods") {
        let params = {
          id: v.id,
          scope: "Inventory_pro_loss_sheet",
        };

        getLatticeInfoForScan(params).then((res) => {
          if (res.code == 200 && res.result) {
            if (res.result.length == 0) {
              this.$toast("该库位关联物品为空");
              return;
            }

            let newGoodsList = res.result.map((son) => {
              let {
                goodsCode,
                goodsName,
                goodsId,
                spec,
                unitName,
                packageSpec,
                address,
                batchCode,
                goodsBatchId,
                latticeId,
                latticeName,
                latticeCode,
              } = son;

              return {
                detailId: "",

                goodsKey: goodsId + "_" + Math.floor(Math.random() * 1000), // 物品基本数据
                goodsId: goodsId || "",

                goodsCode: goodsCode || "",
                goodsName: goodsName || "",
                goodsSpec: spec || "",

                packageSpec: packageSpec || "",
                address: address || "",
                unitIdText: unitName || "",

                batchCode: batchCode || "", // 批次数据
                goodsBatchId: goodsBatchId || "",

                latticeCode: latticeCode || "", // 库位数据
                latticeName: latticeName || "",
                latticeId: latticeId || "",
                latticeFullname:
                  latticeCode && latticeName
                    ? latticeCode + "|" + latticeName
                    : "",
                profitNum: '', // 盘盈数
              };
            });

            if (this.entryDetails.length != 0) {
              let array1Copy = this.mergeWithoutDuplicatesPreservingOriginals(
                this.entryDetails,
                newGoodsList
              );
              if (array1Copy.length != 0) {
                this.entryDetails = this.entryDetails.concat(array1Copy);
              } else {
                this.$toast("物品、批号、盘点库位已存在");
              }
            } else {
              this.entryDetails = newGoodsList;
            }
          } else {
            this.$toast(res.message);
          }
        });
      }
    },
    // 扫库位码 获取库位物品 数据处理
    mergeWithoutDuplicatesPreservingOriginals(arr1, arr2) {
      // 输入校验
      if (!Array.isArray(arr1) || !Array.isArray(arr2)) {
        throw new Error("输入必须为数组");
      }

      // 创建一个哈希表用于存储arr1中元素的索引
      const arr1IndexMap = new Map();
      arr1.forEach((item, index) => {
        if (!arr1IndexMap.has(item.goodsId)) {
          arr1IndexMap.set(item.goodsId, index);
        }
      });

      // 创建arr1的一个浅拷贝
      const newArray = [...arr1];
      let newList = [];

      // 遍历arr2
      arr2.forEach((item) => {
        const arr1Index = arr1IndexMap.get(item.goodsId);

        // 如果arr2中的元素在arr1中不存在，则加入到新列表中
        if (arr1Index === undefined) {
          newList.push(item);
        } else {
          // 比较arr1和arr2中相同goodsId的元素的其他属性
          const arr1Item = newArray[arr1Index];
          if (
            arr1Item.goodsBatchId !== item.goodsBatchId ||
            arr1Item.latticeId !== item.latticeId
          ) {
            newList.push(item);
          }
        }
      });
      // 将arr1中未在arr2中出现的元素加入到新列表中
      newArray.forEach((item) => {
        if (!arr1IndexMap.has(item.goodsId)) {
          newList.push(item);
        }
      });

      return newList;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
@import "@/views/workManagement/materialRequisition/materialForm.scss";
.form-content {
  width: 100%;
  height: calc(100vh - 203px);
  background: #f5f5f5;
  overflow: scroll;
  padding: 20px 0;
  .formgroup {
    background: #ffffff;
    margin-top: 0.1rem;
    margin-bottom: 0.2rem;
    padding-top: 0.1rem;

    .title {
      width: 0.58rem;
      height: 0.14rem;
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
      line-height: 0.05rem;
      margin-left: 0.16rem;
    }
  }
  .search-bottoms {
    width: 100%;
    height: 100px;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: 0px;
    padding: 0rem 11px;
    box-sizing: border-box;
    font-size: 32px;
    font-weight: 500;
    z-index: 9;
    .btnconfirm {
      flex: 1;
      background: #1890ff;
      box-sizing: border-box;
      height: 78px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 6px;
      color: #ffffff;
    }
  }
}
.bottomLine {
  height: 1px;
  background-color: #f2f2f2;
  margin: 0 2px;
}
.haveUnitBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding-right: 32px;
  /deep/ .van-cell {
    padding-right: 0;
    width: 600px;
  }
  /deep/ .van-field__control {
    max-width: 700px;
    // text-align: right;
  }
}
/deep/ .van-nav-bar {
  z-index: 99;
}
/deep/.van-sidebar-item--select::before {
  color: #1890ff;
  background-color: #1890ff;
}
/deep/.van-tree-select__item--active {
  color: #1890ff;
}
.addGoodScontain {
  display: flex;
  flex-wrap: nowrap;
  .addgoods {
    flex: 1;
    background: #fff;
    font-size: 32px;
    text-align: center;
    height: 78px;
    line-height: 78px;
    color: #1890ff;
  }
}
.required span::after {
  left: -20px;
  top: 3px;
}
.filedClear {
  width: 28px;
  height: 28px;
}
.formItemFlex {
  display: flex;
  flex-direction: row;
  .FormTit {
    flex: 1;
    min-width: 3.3rem;
    padding-top: 0.33rem;
  }
  .haveUnitBox {
    flex: 1;
    .van-cell {
      width: 6.2rem;
    }
  }
}
.list {
  margin-top: 10px;
  .wrap {
    background: #fff;
    margin-top: 20px;
    width: 100vw;
    .otherText {
      display: flex;
      justify-content: space-between;
      font-size: 32px;
      font-weight: bold;
      color: #191f25;
      .deleteStyle {
        font-weight: 400;
        color: #ff4d4f;
      }
    }
    .top {
      display: flex;
      justify-content: flex-start;
      padding-top: 10px;
      .icon {
        width: 6px;
        height: 32px;
        background: #1890ff;
        margin: 6px 10px 0 10px;
      }
      .title {
        width: 602px;
        margin-right: 20px;
        font-size: 30px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #191f25;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .titleWidth {
        width: 572px;
      }
    }
    .center {
      p {
        margin: 16px 25px;
        font-size: 28px;
        display: flex;
        position: relative;
        .key {
          color: #888888;
        }
        .value {
          color: #191f25;
          width: 380px;
          display: block;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .arrow {
          color: #1890ff;
          position: absolute;
          right: -10px;
        }
      }
      .showAll {
        background: #f5f8ff;
        width: 100vw;
        margin-left: -30px;
        padding: 30px;
        margin-bottom: 30px;
      }
      .showAll2 {
        width: 100%;
        margin: 0 0 30px 0;
        padding: 30px 0;
      }
    }
  }
}
</style>
